package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.media.RingtoneManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.view.marginTop
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.github.chrisbanes.photoview.PhotoView
import com.google.gson.JsonObject
import com.xw.banner.loader.ImageLoader
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomSignDailog
import com.zat.mes.andrmes.customerview.PicDailog
import com.zat.mes.andrmes.data.PackBean
import com.zat.mes.andrmes.data.PaiZaiBean
import com.zat.mes.andrmes.data.ParantTypeItem
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.vm.GetPackModel
import com.zat.mes.andrmes.dofun.work.vm.HouseModel
import com.zat.mes.andrmes.global.CompanionCode
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.GlideUtil
import com.zat.mes.andrmes.utils.ReadCardUtils
import com.zat.mes.andrmes.utils.SystemActivityUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_style_extra_file.*
import kotlinx.android.synthetic.main.layout_title.*
import kotlinx.android.synthetic.main.show_photo_view.view.*
import org.json.JSONObject
import permissions.dispatcher.*

/**
 * 款式资料 查看
 */
@RuntimePermissions
class StyleExtraFileActivity : BaseActivity() {

    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null
    //仓库类型
    var house: MutableList<ParantTypeItem>? = null
    var qcModel: QcPlanViewModel? = null
    var houseModel: HouseModel? = null
    //var packBean: PackBean? = null
    var packBean: PaiZaiBean? = null
    private var getPackModel: GetPackModel? = null

    override fun init() {
        initView()
        initData()
    }

    private fun initView() {
        setContentView(R.layout.activity_style_extra_file)
        tVtitle.text = "款式资料"
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }

        btnScanStyleExtra.setOnClickListener {
            showCameraWithPermissionCheck()
        }

    }

    private fun initData() {
//读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()

        houseModel = ViewModelProvider(this).get(HouseModel::class.java)
        houseModel?.getPackData()?.observe(this, Observer {

//            packBean = it
//            tvOrderNumStyleExtra.text = "制单号："+packBean?.cancelEmp
//            //查询资料
//            houseModel?.loadStyleExtraFileData(packBean?.cancelEmp)


        })
        getPackModel = ViewModelProvider(this).get(GetPackModel::class.java)
        getPackModel?.getPaiZaiData()?.observe(this, Observer {
            closeLoading()
            if (it != null) {
                packBean = it
                tvOrderNumStyleExtra.text = "制单号："+packBean?.orderNo
                //查询资料
                houseModel?.loadStyleExtraFileData(packBean?.orderNo)
            }
        })
        houseModel?.getStyleData()?.observe(this, Observer {
            closeLoading()
            if (it!=null){
               if (!TextUtils.isEmpty(it.threadings)){
                   val split = it.threadings.split(",")
                   setImage(llcsdStyleExtra,split)
               }
                if (!TextUtils.isEmpty(it.sews)){
                   val split = it.sews.split(",")
                   setImage(llfzyqStyleExtra,split)
               }
                if (!TextUtils.isEmpty(it.positions)){
                   val split = it.positions.split(",")
                   setImage(llbwlfStyleExtra,split)
               }
                if (!TextUtils.isEmpty(it.inspections)){
                   val split = it.inspections.split(",")
                   setImage(llzjyqdStyleExtra,split)
               }
                if (!TextUtils.isEmpty(it.cylinders)){
                   val split = it.cylinders.split(",")
                   setImage(llpgmxStyleExtra,split)
               }
            }

        })

    }
    fun setImage(linearLayout: LinearLayout,split:List<String>){
        linearLayout.removeAllViews()
        if(split.size>0) {
            for (i in 0..split.size - 1) {
                val imageView = ImageView(this)
                imageView.layoutParams = LinearLayout.LayoutParams(400,400)
                imageView.setPadding(10,10,10,10)
                linearLayout.addView(imageView)
                Glide.with(this).load(split[i]).into(imageView)
                imageView.setOnClickListener {
                   PicDailog(this,split[i]).show()

                }
            }
        }
    }

    /**
     * 初始化刷卡器
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
                showLoading()
                houseModel?.loadPackDataByRFRD(it)
            }
        })

    }

    /**
     * 设备刷卡监听
     */
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
           // houseModel?.loadPackData(qrCode)
            getPackModel?.paiZaiInfo(qrCode!!)
        }
    }




    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(
                Intent(this, QrScanActivity::class.java),
                CompanionCode.REQUESTCODE
            )
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }
}
